package com.example.websocket.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.example.websocket.config.ConstConfig;
import com.example.websocket.model.ChatMessage;
import com.example.websocket.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
public class ChatController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @MessageMapping("/chat.sendMessage")
    public void sendMessage(@Payload ChatMessage chatMessage) {
        redisTemplate.convertAndSend(ConstConfig.MSG_TO_ALL_KEY, JSON.toJSONString(chatMessage, JSONWriter.Feature.WriteEnumsUsingName));
    }

    @MessageMapping("/chat.addUser")
    public void addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        redisTemplate.opsForSet().add(ConstConfig.ONLINE_USER_KEY, chatMessage.getSender());
        redisTemplate.convertAndSend(ConstConfig.CHANNEL_TOPIC_KEY, JSON.toJSONString(chatMessage, JSONWriter.Feature.WriteEnumsUsingName));
    }

}

